package com.ncdnapp.dao;

import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.util.ClassUtil;
import com.mybatisflex.core.util.SqlUtil;

import java.io.Serializable;
import java.util.Collection;

public interface BaseDao<T> extends BaseMapper<T> {
    default Boolean selectExistsById(Serializable id) {
        QueryWrapper queryWrapper = QueryWrapper.create().eq("id", id);
        long count = selectCountByQuery(queryWrapper);
        if (count > 0L) {
            return true;
        }
        return false;
    }

    /**
     * 批量新增或者更新
     * 有id表示更新,id为null表示新增
     *
     * @param poList
     * @param batchSize
     * @return
     */
    default boolean saveBatch(Collection<T> poList, int batchSize) {
        BaseMapper<T> mapper = this;
        Class<BaseMapper<T>> usefulClass = (Class<BaseMapper<T>>) ClassUtil.getUsefulClass(mapper.getClass());
        return SqlUtil.toBool(Db.executeBatch(poList, batchSize, usefulClass, BaseMapper::insertOrUpdateSelective));
    }
}
